package com.example.newdemo.net;

import android.util.Log;

import com.example.newdemo.net.api.ApiService;
import com.example.newdemo.net.jsonConverter.JSONConverterFactory;
import com.example.newdemo.net.model.HttpManager;
import com.example.newdemo.utils.LogUtils;

import org.json.JSONObject;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLHandshakeException;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.HttpException;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class OkHttpInitDemo {


    //?type=yuantong
    private final static String url = "http://www.kuaidi100.com/";




    public static void httpInit(){


        OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)// connect timeout
                .connectTimeout(30, TimeUnit.SECONDS)// socket timeout
                .retryOnConnectionFailure(true);


        okHttpBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                String content = ""; // 后续添加缓存的 toking_content
                Request.Builder builder = chain.request().newBuilder()
                        .addHeader("Content-Type", "text/plain;charset=utf-8")
                        .addHeader("content", content == null ? "" : content);
//                        .addHeader("","android_user")
                return chain.proceed(builder.build());
            }
        });

        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl(url)        // http 地址
                .client(okHttpBuilder.build())
                .addConverterFactory(JSONConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        mRetrofit.create(ApiService.class)
                .getSkuCategories("19","BFxzb94L")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Object>(){
                    @Override
                    public void onNext(@NonNull Object o) {
                        LogUtils.d(o.toString() + "*******************");
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        try {

                            if (e instanceof SocketTimeoutException) {//请求超时
//                                responseCallBack.onFault("请求超时,请稍后再试");
                            } else if (e instanceof ConnectException) {//网络连接超时
//                                responseCallBack.onFault("网络连接超时,请检查网络状态");
                            } else if (e instanceof SSLHandshakeException) {//安全证书异常
//                                responseCallBack.onFault("安全证书异常");
                            } else if (e instanceof HttpException) {//请求的地址不存在
                                int code = ((HttpException) e).code();
                                if (code == 504) {
//                                    responseCallBack.onFault("网络异常，请检查您的网络状态");
                                } else if (code == 404) {
//                                    responseCallBack.onFault("请求的地址不存在");
                                } else {
//                                    responseCallBack.onFault("请求失败");
                                }
                            } else if (e instanceof UnknownHostException) {//域名解析失败
//                                responseCallBack.onFault("域名解析失败");
                            } else {
//                                responseCallBack.onFault("error:" + e.getMessage());
                            }
                        } catch (Exception e2) {
                            e2.printStackTrace();
                        } finally {
                            Log.e("OnSuccessAndFaultSub", "error:" + e.getMessage());
//                            if (disposable !=null && !disposable.isDisposed()){ //事件完成取消订阅
//                                disposable.dispose();
//                            }
//                            if (progressListener!=null){
//                                progressListener.cancelProgress();
//                            }
                        }
                    }

                    @Override
                    public void onComplete() {
                        LogUtils.d("onComplete-------------");
                    }
                });

    }


    private void httpTest() {

        HttpManager manager =HttpManager.getInstance();
        manager.getApiService()
                .getSkuCategories("19","BFxzb94L")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<JSONObject>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        LogUtils.d("******onSubscribe***********");
                    }

                    @Override
                    public void onNext(@NonNull JSONObject jsonObject) {
                        LogUtils.d(jsonObject.toString());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        LogUtils.d("--------------------onComplete");
                    }
                });

    }


}
